package service

import (
	"dsc-server/domain/dto"
	"dsc-server/pkg/model"
	"encoding/json"
	"fmt"
	"gorm.io/gorm"
	"time"
)

// ApiConfigService 处理API配置相关的服务
type ApiConfigService struct {
	DB *gorm.DB
}

// NewApiConfigService 创建ApiConfigService实例
func NewApiConfigService(db *gorm.DB) *ApiConfigService {
	return &ApiConfigService{DB: db}
}

// Add 添加API配置
func (s *ApiConfigService) Add(apiConfig *model.ApiConfig) dto.Result {
	var count int64
	s.DB.Model(&model.ApiConfig{}).Where("path = ? AND is_deleted = 0", apiConfig.Path).Count(&count)

	if count > 0 {
		return dto.FailureMessage(nil, "该路径已被使用，请修改请求路径再保存")
	}

	apiConfig.Status = 0
	if err := s.DB.Create(apiConfig).Error; err != nil {
		return dto.FailureMessage(nil, fmt.Sprintf("添加失败: %v", err))
	}

	return dto.SuccessMessage(nil, "添加成功")
}

// Update 更新API配置
func (s *ApiConfigService) Update(apiConfig *model.ApiConfig) dto.Result {
	var count int64
	s.DB.Model(&model.ApiConfig{}).
		Where("path = ? AND id != ? AND is_deleted = 0", apiConfig.Path, apiConfig.ID).
		Count(&count)

	if count > 0 {
		return dto.FailureMessage(nil, "该路径已被使用，请修改请求路径再保存")
	}

	if err := s.DB.Model(&model.ApiConfig{}).Where("id = ?", apiConfig.ID).Updates(apiConfig).Error; err != nil {
		return dto.FailureMessage(nil, fmt.Sprintf("修改失败: %v", err))
	}

	// 清除缓存
	// TODO: 实现缓存清除逻辑

	return dto.SuccessMessage(nil, "修改成功")
}

// Delete 删除API配置
func (s *ApiConfigService) Delete(id uint, path string) dto.Result {
	if err := s.DB.Model(&model.ApiConfig{}).Where("id = ?", id).Update("is_deleted", 1).Error; err != nil {
		return dto.FailureMessage(nil, fmt.Sprintf("删除失败: %v", err))
	}

	// 清除缓存
	// TODO: 实现缓存清除逻辑

	return dto.SuccessMessage(nil, "删除成功")
}

// Detail 获取API配置详情
func (s *ApiConfigService) Detail(id uint) (*model.ApiConfig, error) {
	var apiConfig model.ApiConfig
	result := s.DB.Where("id = ? AND is_deleted = 0", id).First(&apiConfig)
	return &apiConfig, result.Error
}

// GetAll 获取所有API配置
func (s *ApiConfigService) GetAll() ([]*model.ApiConfig, error) {
	var apiConfigs []*model.ApiConfig
	result := s.DB.Where("is_deleted = 0").Find(&apiConfigs)
	return apiConfigs, result.Error
}

// GetAllDetail 获取所有API配置详情（按分组）
func (s *ApiConfigService) GetAllDetail() ([]gin.H, error) {
	type ApiDto struct {
		ID           uint   `json:"id"`
		Path         string `json:"path"`
		Name         string `json:"name"`
		Note         string `json:"note"`
		Status       int    `json:"status"`
		DatasourceID int    `json:"datasource_id"`
		GroupID      int    `json:"group_id"`
		GroupName    string `json:"group_name"`
	}

	var apiDtos []ApiDto

	// 联合查询API配置和分组信息
	err := s.DB.Table("api_config ac").
		Select("ac.id, ac.path, ac.name, ac.note, ac.status, ac.datasource_id, ac.group_id, ag.name as group_name").
		Joins("left join api_group ag on ac.group_id = ag.id").
		Where("ac.is_deleted = 0").
		Find(&apiDtos).Error

	if err != nil {
		return nil, err
	}

	// 按分组名称分组
	groupMap := make(map[string][]ApiDto)
	for _, api := range apiDtos {
		groupMap[api.GroupName] = append(groupMap[api.GroupName], api)
	}

	// 构建返回结果
	var result []gin.H
	for groupName, apis := range groupMap {
		result = append(result, gin.H{
			"name":     groupName,
			"children": apis,
		})
	}

	return result, nil
}

// Search 搜索API配置
func (s *ApiConfigService) Search(keyword string, field string, groupID string) ([]*model.ApiConfig, error) {
	query := s.DB.Model(&model.ApiConfig{}).Where("is_deleted = 0")

	if keyword != "" && field != "" {
		query = query.Where(fmt.Sprintf("%s LIKE ?", field), "%"+keyword+"%")
	}

	if groupID != "" {
		query = query.Where("group_id = ?", groupID)
	}

	var apiConfigs []*model.ApiConfig
	err := query.Find(&apiConfigs).Error
	return apiConfigs, err
}

// GetConfig 获取在线API配置
func (s *ApiConfigService) GetConfig(path string) (*model.ApiConfig, error) {
	var apiConfig model.ApiConfig
	result := s.DB.Where("path = ? AND status = 1 AND is_deleted = 0", path).First(&apiConfig)
	return &apiConfig, result.Error
}

// Online 上线API配置
func (s *ApiConfigService) Online(id uint, path string) dto.Result {
	if err := s.DB.Model(&model.ApiConfig{}).Where("id = ?", id).Update("status", 1).Error; err != nil {
		return dto.FailureMessage(nil, fmt.Sprintf("上线失败: %v", err))
	}

	// 清除缓存
	// TODO: 实现缓存清除逻辑

	return dto.SuccessMessage(nil, "上线成功")
}

// Offline 下线API配置
func (s *ApiConfigService) Offline(id uint, path string) dto.Result {
	if err := s.DB.Model(&model.ApiConfig{}).Where("id = ?", id).Update("status", 0).Error; err != nil {
		return dto.FailureMessage(nil, fmt.Sprintf("下线失败: %v", err))
	}

	// 清除缓存
	// TODO: 实现缓存清除逻辑

	return dto.SuccessMessage(nil, "下线成功")
}

// GetPath 获取API路径
func (s *ApiConfigService) GetPath(id uint) (string, error) {
	var apiConfig model.ApiConfig
	result := s.DB.Select("path").Where("id = ? AND is_deleted = 0", id).First(&apiConfig)
	return apiConfig.Path, result.Error
}

// ApiDocs 生成API文档
func (s *ApiConfigService) ApiDocs(ids []uint) (string, error) {
	var apiConfigs []model.ApiConfig
	if err := s.DB.Where("id IN ? AND is_deleted = 0", ids).Find(&apiConfigs).Error; err != nil {
		return "", err
	}

	doc := "# 接口文档\n---\n"

	for _, api := range apiConfigs {
		doc += fmt.Sprintf("## %s\n- 接口地址： /api/%s\n- 接口备注：%s\n- 请求参数：",
			api.Name, api.Path, api.Note)

		var params []map[string]interface{}
		if err := json.Unmarshal([]byte(api.Params), &params); err != nil {
			continue
		}

		if len(params) > 0 {
			doc += "\n\n| 参数名称 | 参数类型 | 参数说明 |\n"
			doc += "| :----: | :----: | :----: |\n"

			for _, param := range params {
				name := param["name"].(string)
				paramType := param["type"].(string)
				if paramType[:5] == "Array" {
					paramType = paramType[6:len(paramType)-1] + "数组"
				}
				note := param["note"].(string)
				doc += fmt.Sprintf("|%s|%s|%s|\n", name, paramType, note)
			}
		} else {
			doc += "无参数\n"
		}

		doc += "\n---\n"
	}

	doc += "\n导出日期：" + time.Now().Format("2006-01-02 15:04:05")
	return doc, nil
}
